// index.js
// 获取应用实例
const main = require('../../models/main');
const ad = require('../../models/ad');
const search = require('../../models/search');

Page({
  data: {
    m: "Nike",//首页展示的鞋品，值为数据库的表名
    value: [],
    adMsg: {},
    searchResult: [],
    option1: [
      { text: '全部商品', value: 0 },
      { text: '新款商品', value: 1 },
      { text: '活动商品', value: 2 },
    ],
    option2: [
      { text: '默认排序', value: 'a' },
      { text: '价格升序', value: 'b' },
      { text: '价格降序', value: 'c' },
      { text: '销量升序', value: 'd' },
      { text: '销量降序', value: 'e' },
    ],
    value1: 0,
    value2: 'a',
  },
  async onLoad(options) {
    // 初始化缓存nav的值
    wx.setStorageSync('nav', "Nike")
    await this.getValue(this.data.m)

    // 获取广告信息
    var adMsg = await ad();
    this.setData({
      adMsg: adMsg.data.res
    })
    console.log(this.data.value);

  },
  async onShow() {
    var m = wx.getStorageSync('nav');
    this.setData({
      m,
    })
    await this.getValue(this.data.m)
  },
  onPullDownRefresh:async function () {
    //调用刷新时将执行的方法
    wx.showLoading({
      title: '刷新中...',
    })
    wx.setStorageSync('nav', "Nike")
    await this.getValue(this.data.m)
  },

  // 获取球鞋列表
  async getValue(m) {
    var data = await main(m);
    this.setData({
      value: data.data.res
    })
  },
  getId(event) {
    console.log(event.detail);
  },
  // 排序
  async onChange(event) {
    console.log(event.detail);
    if (event.detail == "a") {
      await this.getValue("Nike")
    } else if (event.detail == "b") {
      // 价格升序
      this.data.value.sort((a, b) => {
        return a.price - b.price
      })
    } else if (event.detail == "c") {
      // 价格降序
      this.data.value.sort((a, b) => {
        return b.price - a.price
      })
    } else if (event.detail == "d") {
      // 销量升序
      this.data.value.sort((a, b) => {
        return a.sold - b.sold
      })
    } else if (event.detail == "e") {
      // 销量降序
      this.data.value.sort((a, b) => {
        return b.sold - a.sold
      })
    }
    this.setData({
      value: this.data.value
    })
  },

  // 搜索
  async onSearch(event) {
    // console.log(event.detail);
    var data = await search(event.detail.trim());
    if (event.detail.trim()) {
      this.setData({
        searchResult: data.data
      })
    } else {
      this.setData({
        searchResult: []
      })
    }
  },

  // 跳转到分类页
  toNav() {
    wx.navigateTo({
      url: '../nav/nav',
    })
  }
})
